package mavenWebProject;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * Servlet implementation class AddToCarServlet
 */
@WebServlet("/AddToCarServlet")
public class AddToCarServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddToCarServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
				request.setCharacterEncoding("UTF-8");
				String name=request.getParameter("name");
				String img=request.getParameter("img");
				String size=request.getParameter("size");
				String price=request.getParameter("price");
				String amount=request.getParameter("num");
				HttpSession session=request.getSession();
				String username=(String) session.getAttribute("username");
				//1.加载mybatis的核心配置文件，获取sqlsessionfactory
				String resource = "mybatis-config.xml";
				InputStream inputStream = Resources.getResourceAsStream(resource);
				SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
				
				//2.获取sqlsession对象，用它来执行sql
				SqlSession sqlsession=sqlSessionFactory.openSession();
				
				//3.获取mapper接口的代理对象
				productsMapper mapper=sqlsession.getMapper(productsMapper.class);
				List<car> car=mapper.selectCarByNameSize(name,size);
				if(car.isEmpty()) {
					mapper.insertIntoCar(name, Integer.valueOf(price.trim()), Integer.valueOf(amount.trim()), size,img,username);
					request.getRequestDispatcher("messagePage.jsp?message=成功加入购物车").forward(request, response);
				}else {
					int temp=0;
					for(car s:car) {
						temp=Integer.valueOf(amount.trim())+s.getAmount();
					}
					mapper.updateCarGoodAmount(temp,name,size,username);
					request.getRequestDispatcher("messagePage.jsp?message=该商品又增加了").forward(request, response);
				}
				sqlsession.commit();
				sqlsession.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
